Page({
  data: {
    voteBoxType: false, 
    voteBoxTitle: '',
    voteBoxDesc: '',
    optionList: [],
    optionImgList: [],
    startDate:'',
    startTime: '',
    startDateAndTime:'',
    isMultipleChoice: false,
    buttonDisable: false
  },
  onLoad(options) {
    this.formReset();
  },
  onTitleInputChange(e) {
    this.setData({
      voteBoxTitle: e.detail.value
    })
  },
  onDescChange(e) {
    this.setData({
      voteBoxDesc: e.detail.value
    })
  },
  onTapAddOption(e) {
    const newOptionList = this.data.optionList
    const newOptionImgList = this.data.optionImgList
    newOptionList.push('')
    newOptionImgList.push('null')
    this.setData({
      optionList: newOptionList,
      optionImgList: newOptionImgList, 
    })
  },
  onOptionInputChange(e) {
    const newOptionList = this.data.optionList
    const changedIndex = e.currentTarget.dataset.optionIndex
    newOptionList[changedIndex] = e.detail.value
    this.setData({
      optionList: newOptionList
    })
  },
  onTapDelOption(e) {
    const delIndex = e.currentTarget.dataset.optionIndex
    const newOptionList = this.data.optionList.filter(
      (v, i) => i !== delIndex
    )
    const newOptionImgList = this.data.optionImgList.filter(
      (v,i) => i != delIndex
    )
    this.setData({
      optionList: newOptionList,
      optionImgList: newOptionImgList
    })
  },

 onChangeStartDate(e) {
  const startDate = e.detail.value;
  const startTime = this.data.startTime;
  const startDateAndTime = startDate + ' ' + startTime;
  this.setData({
    startDate: startDate,
    startDateAndTime: startDateAndTime
  })
},

onChangeStartTime(e) {
  const startDate = this.data.startDate;
  const startTime = e.detail.value;
  const startDateAndTime = startDate + ' ' + startTime;
  this.setData({
    startTime: startTime,
    startDateAndTime: startDateAndTime
  })
},

  onChangeIsMultipleChoice(e) {
    this.setData({
      isMultipleChoice: e.detail.value
    })
  },
  // 校验表单数据是否完整，如果校验通过就返回null，否则返回需要提示的文字
  checkFormValid() {
    if (!this.data.voteBoxTitle) {
      return '标题不能为空'
    }
    if (this.data.optionList.length < 2) {
      return '至少需要2个选项'
    }
    for (let i = 0; i < this.data.optionList.length; i++) {
      if (!this.data.optionList[i]) {
        return '选项不能为空'
      }
    }
    return null
  },
  formSubmit() {

    wx.showLoading({
      title: '加载中',
      mask:true
    })
    // 提交前需要先对表单内容进行校验
    const msg = this.checkFormValid();
    if (msg) {        // 在if判断时，null会被转换为false
      wx.showToast({  // 调用提示框API显示提示内容
        title: msg,   // 提示框中的文字内容
        icon: 'none'  // 提示框的图标，none表示没有图标
      })


      return           // 提前返回，函数会在这里结束，后面的内容不会执行
    }
    // 校验通过时后面的内容才会被执行
    const formData = {  // 将表单的数据放到一个formData对象中
      voteBoxType: this.data.voteBoxType,
      voteBoxTitle: this.data.voteBoxTitle,
      voteBoxDesc: this.data.voteBoxDesc,
      optionList: this.data.optionList,
      optionImgList: this.data.optionImgList,
      startDateAndTime: this.data.startDateAndTime,
      isMultipleChoice: this.data.iswMultipleChoice,
    }
     console.log(formData)

      wx.setStorageSync('startDateAndTime', this.data.startDateAndTime);
      wx.setStorageSync('isMultipleChoice', this.data.isMultipleChoice);

      let self = this;
    wx.request({
      url: "https://www.intohash.com/vote_backend/user/addBoxVote",
      // url: "http://localhost:8001/vote_backend/user/addBoxVote",
        method:"POST",
        data:{
        "optionList": this.data.optionList,
        "startDate": this.data.startDateAndTime,
          "title": this.data.voteBoxTitle,
          "type": this.data.voteBoxType?1:0,
          "userId": wx.getStorageSync('userid'),
          "voteDesc": this.data.voteBoxDesc,
          "voteType": 2,
        },
        success: function (e) {
            //返回userid 用户评论
            console.log(e)
            wx.hideLoading()
            if(e.data.success == true){ // 调用合约成功
              console.log("合约调用成功");

              self.setData({
                buttonDisable:!self.data.buttonDisable,
              })

              let voteId = e.data.data;
              wx.redirectTo({       // 自动跳转到添加投票人页面
                url: '/pages/addVoteBoxVoter/addVoteBoxVoter?voteId=' + voteId,
              }) 
          }
          else{
            console.log("合约调用失败");
            wx.showToast({  
              title: "未能成功创建投票箱",   
              icon: 'none'  
            })
          }
        }
      , fail: function (e) {
        // this.setData({
        //   buttonDisable:!self.data.buttonDisable,
        // })
        wx.hideLoading()
        console.error(e)
        wx.showToast({            // 创建投票失败时，显示提示框提示用户
          title: '未能成功创建投票箱',  // 提示框中的文字内容
          icon: 'none'            // 提示框的图标，none表示没有图标
        })
      }
    });
  },
  onTapFormResetBtn() {
    let self = this;
    wx.showModal({

      title: '重置',
 
      content: '您确定要重置所有内容吗？',
 
      success: function (res) {
 
        if (res.confirm) {//这里是点击了确定以后
          self.formReset();

        } else {//这里是点击了取消以后

        }
      },
      fail:function(res){

      }
    })
},


formReset(){
  const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth()+1
    const nowDay = now.getDate()
    const nowHour = now.getHours();
    const nowMinute = now.getMinutes();

    const startDate = nowYear +
    '-' +
    ((nowMonth < 10) ? ('0' + nowMonth) : nowMonth) +
    '-' +
    ((nowDay < 10) ? ('0' + nowDay) : nowDay);


     const startTime = ((nowHour < 10)?('0' + nowHour) : nowHour) +
     ':' +
     ((nowMinute < 10)?('0' + nowMinute) : nowMinute) ;
     
    this.setData({

      voteBoxType: false, 
      voteBoxTitle: '',
      voteBoxDesc: '',
      optionList: [],
      optionImgList: [],
      startDate,
      startTime,
      startDateAndTime: startDate + ' ' + startTime,
      isMultipleChoice: false,
    })
  }
})